package com.ddz.controller;

import com.ddz.service.GameMsgService;
import com.ddz.service.GameRoomManager;
import com.ddz.model.User;
import com.ddz.service.UserService;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;


@ServerEndpoint("/game/{roomId}/{playerId}")
public class GameWebSocket {

    private Session session;
    private String playerId;
    private String roomId;
    private User self_user;

    // 建立连接时调用
    @OnOpen
    public void onOpen(Session session, @PathParam("roomId") String roomId, @PathParam("playerId") String playerId) {
        this.session = session;
        this.roomId = roomId;
        this.playerId = playerId;

        try {
            // 将玩家添加到房间
            System.out.println("Adding players");
            self_user = UserService.selectUser(playerId);
            self_user.setRoomid(roomId);
            self_user.setOrder(GameRoomManager.getRoomPlayerCount(roomId));
            // 判断房间是否已满
            if(GameRoomManager.getRoomPlayerCount(roomId) == 3){
                GameMsgService.error("房间已满！",session);
                return;
            }
            GameRoomManager.addPlayerToRoom(roomId, self_user, session);
        }catch (Exception e){
            System.out.println("添加玩家进入房间时异常");
            System.out.println(e.getMessage());
        }

        // 判断是否有三个玩家进入房间
        if(GameRoomManager.getRoomPlayerCount(roomId) == 3){
            GameMsgService.startMessage(roomId);
        }
    }

    // 接收消息时调用
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            // 设置接收消息延迟
            Thread.sleep(25);
            GameMsgService.handleMessage(message, roomId);
        }catch (Exception e){
            System.out.println("处理玩家消息异常");
            System.out.println(message);
            System.out.println(e.getMessage());
        }

    }

    // 连接关闭时调用
    @OnClose
    public void onClose() {
        try {
            if (GameRoomManager.getPlayerInRoom(roomId,playerId) != null) {
                System.out.println("玩家断开连接，正在尝试关闭房间");
                GameRoomManager.removeRoom(roomId);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    // 错误处理
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }
}
